﻿using System;
using UnityEngine;

namespace UFrame
{
    public class OUUIFollow : MonoBehaviour
    {
        public Transform target;
        public RectTransform rectTrans;
        public Canvas canvas;
        
        public bool isIgnoreX;
        public bool isIgnoreY;
        public float offsetY;
        public float offsetX;

        public Camera main;

        public void Awake()
        {
           
        }

        public void OnEnable()
        {
            CheckData();
        }

        public void CheckData()
        {
            if (rectTrans == null)
                rectTrans = GetComponent<RectTransform>();
            if (main == null)
                main = Camera.main;
        }

        public void SetTarget(Transform t)
        {
            target = t;
            CheckData();
            UpdatePos();
        }

        public void Update()
        {
            UpdatePos();
        }

        public void UpdatePos()
        {
            if (target == null)
                return;
            if (rectTrans == null)
                return;
            if (main == null)
                return;

            
            Vector2 pos = RectTransformUtility.WorldToScreenPoint(main, target.transform.position);
            //pos = UGUITool.ConvertUIPos(canvas, rectTrans, pos, main);
            
            if (isIgnoreY)
            {
                var uiPos = rectTrans.position;
                pos.y = uiPos.y;
            }
            else if (isIgnoreX)
            {
                var uiPos = rectTrans.position;
                pos.x = uiPos.x;
            }

            pos.y += offsetY;
            pos.x += offsetX;

            rectTrans.position = pos;
        }
    }
}